package com.ljx.funchat.chat.service.adapter;

import com.ljx.funchat.chat.domain.dto.RoomBaseInfo;
import com.ljx.funchat.chat.domain.entity.Contact;
import com.ljx.funchat.chat.domain.entity.Room;
import com.ljx.funchat.chat.domain.entity.RoomFriend;
import com.ljx.funchat.chat.domain.entity.RoomGroup;
import com.ljx.funchat.chat.domain.enums.RoomTypeEnum;
import com.ljx.funchat.user.domain.entity.User;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class ContactAdapter {
    public static Map<Long, RoomBaseInfo> buildRoomBaseInfo(Map<Long, Room> roomMap, Map<Long, RoomGroup> groupRoomMap,
                                                       Map<Long, User> userMap, Map<Long, RoomFriend> roomFriendMap,
                                                       Long uid) {
        return roomMap.values().stream().map(item -> {
            RoomBaseInfo roomBaseInfo = new RoomBaseInfo();
            roomBaseInfo.setRoomId(item.getId());
            roomBaseInfo.setType(item.getType());
            roomBaseInfo.setActiveTime(item.getActiveTime());
            roomBaseInfo.setLastMsgId(item.getLastMsgId());
            if (item.getType().equals(RoomTypeEnum.FRIEND.getType())){
                RoomFriend roomFriend = roomFriendMap.get(item.getId());
                Long friendId = uid.equals(roomFriend.getUid1()) ? roomFriend.getUid2() : roomFriend.getUid1();
                User user = userMap.get(friendId);
                roomBaseInfo.setName(user.getName());
                roomBaseInfo.setAvatar(user.getAvatar());
            }
            if (item.getType().equals(RoomTypeEnum.GROUP.getType())) {
                RoomGroup roomGroup = groupRoomMap.get(item.getId());
                roomBaseInfo.setName(roomGroup.getName());
                roomBaseInfo.setAvatar(roomGroup.getAvatar());
            }
            return roomBaseInfo;
        }).collect(Collectors.toMap(RoomBaseInfo::getRoomId, Function.identity()));
    }

    public static Contact buildContactFirstSave(Long uid) {
        Contact contact = new Contact();
        contact.setUid(uid);
        contact.setRoomId(1L); // 默认全员群
        contact.setReadTime(new Date());
        return contact;
    }
}
